package com.james.happyfarm.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.james.happyfarm.JDO.Message;
import com.james.happyfarm.JDO.PMF;

public class Rss extends HttpServlet {

	private static final long serialVersionUID = 1657676766352306416L;
	  
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
		
		StringBuffer rss = new StringBuffer();
		rss.append("<?xml version=\"1.0\"?>");
		rss.append("<rss version=\"2.0\">");
		rss.append("<channel>");
		rss.append("<title>KaiXin001</title>");
		rss.append("<link>http://www.kaixin001.com</link>");
		rss.append("<description></description>");
		
		try {
			String query = "select from " + Message.class.getName() + " where date >= yesterday PARAMETERS Date yesterday import java.util.Date order by date desc";
			Date yesterday = new Date(Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")).getTimeInMillis() - 2*24*3600*1000);
			List<Message> msgList = (List<Message>)pm.newQuery(query).execute(yesterday);
			
			for (Message msg : msgList) {
				rss.append("<item>");
				rss.append("<title>from " + msg.getFrom() + "</title>");
				rss.append("<description>" + msg.getMsg() + "</description>");
				rss.append("<pubDate>" + sdf.format(msg.getDate()) + "</pubDate>");
				rss.append("</item>");
			}
			rss.append("</channel>");
			rss.append("</rss>");
			
			resp.setCharacterEncoding("UTF-8");			
			PrintWriter pw = resp.getWriter();
			pw.write(rss.toString());			
			pw.flush();	
			
		} finally {			
			pm.close();
		}
	}
}
